package com.ruoyi.system.service.impl;

import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.UserInfo;
import com.ruoyi.system.mapper.UserInfoMapper;
import com.ruoyi.system.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.web.client.RestTemplate;
/**
 * 试用申请管理Service业务层处理
 *
 * @author hak
 * @date 2024-11-13
 */
@Service
public class UserInfoServiceImpl implements IUserInfoService
{
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 微信登录
     * @param loginCode 微信登录code
     * @return 用户信息
     */
    @Override
    public UserInfo loginByWeChat(String loginCode) {
        // 1. 调用微信API获取openid和session_key
        // 这里需要实现微信API的调用逻辑
        // 示例代码:

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}&grant_type=authorization_code";

        Map<String, String> params = new HashMap<>();
        params.put("appid", "wx80bf8ed12a3d8130");
        params.put("secret", "3f869547c44af0ea6cb507cd791a33be");
        params.put("js_code", loginCode);
        String openId = "mock_openid_" + System.currentTimeMillis();
        String sessionKey = "mock_session_key_" + System.currentTimeMillis();
        String unionId = "mock_unionid_" + System.currentTimeMillis();
        try {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class,params);
            JSONObject json = JSONObject.parseObject(response.getBody());

            if (json.containsKey("errcode")) {
                throw new RuntimeException("微信登录失败: " + json.getString("errmsg"));
            }
            openId = json.getString("openid");
            sessionKey = json.getString("session_key");
        } catch (Exception e) {
            throw new RuntimeException("调用微信API失败", e);

        }

        // 2. 解析微信返回结果
        // JSONObject json = JSON.parseObject(response);
        // String openId = json.getString("openid");
        // String sessionKey = json.getString("session_key");
        // String unionId = json.getString("unionid");

        // 模拟数据
//        String openId = "mock_openid_" + System.currentTimeMillis();
//        String sessionKey = "mock_session_key_" + System.currentTimeMillis();
//        String unionId = "mock_unionid_" + System.currentTimeMillis();

        // 3. 查询或创建用户
        UserInfo userInfo = userInfoMapper.selectUserInfoByOpenId(openId);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(UUID.randomUUID().toString());
            userInfo.setOpenId(openId);
            userInfo.setUnionId(unionId);
            userInfo.setSessionKey(sessionKey);
            userInfo.setStatus(0); // 默认正常状态
            userInfoMapper.insertUserInfo(userInfo);
        } else {
            // 更新session_key
            userInfo.setSessionKey(sessionKey);
            userInfoMapper.updateUserInfoByLogin(userInfo);
        }

        return userInfo;
    }

    @Override
    public UserInfo selectUserInfoByUserId(String userId) {
        return userInfoMapper.selectUserInfoByUserId(userId);
    }

    @Override
    public int updateUserInfo(UserInfo userInfo) {
        // 校验用户ID是否存在
        UserInfo existingUser = userInfoMapper.selectUserInfoByUserId(userInfo.getUserId());
        if (existingUser == null) {
            throw new ServiceException("用户不存在");
        }

        // 只更新允许修改的字段
        UserInfo updateInfo = new UserInfo();
        updateInfo.setUserId(userInfo.getUserId());
        if (StringUtils.isNotBlank(userInfo.getOpenId())) {
            updateInfo.setOpenId(userInfo.getOpenId());
        }
        if (StringUtils.isNotBlank(userInfo.getUnionId())) {
            updateInfo.setUnionId(userInfo.getUnionId());
        }
        if (StringUtils.isNotBlank(userInfo.getSessionKey())) {
            updateInfo.setSessionKey(userInfo.getSessionKey());
        }
        if (StringUtils.isNotBlank(userInfo.getPhoneNumber())) {
            updateInfo.setPhoneNumber(userInfo.getPhoneNumber());
        }

        return userInfoMapper.updateUserInfo(updateInfo);
    }
}
